#!/usr/bin/env python
# -*- coding: utf-8 -*-
from itertools import izip_longest
import sys,os
import Queue
from threading import Timer
from subprocess import Popen, PIPE
import signal
import time

class Alarm(Exception):
	pass

def alarm_handler(signum,frame):
	raise Alarm

Archivo = "/home/mmoltrasio/" + time.strftime("%Y%m%d%H%M%S",time.localtime()) + "_salida.txt"
guardaren = open(Archivo,'w')
guardaren.close()


signal.signal(signal.SIGALRM, alarm_handler)
signal.alarm(1)

def obtenerCadenas(pipe):
	cola = Queue.Queue()
	while True:
		try:

			signal.alarm(1)
			try:
				cadena = pipe.stdout.read(1)
				if cadena != "":
					cola.put(cadena)
			except Alarm:
				if not cola.empty():
					convertir(cola)
		except KeyboardInterrupt:
			pipe.kill()
			pipe = Popen(["sh","permisos.sh"])
			pipe.wait()
			sys.exit(0)


def grouper(n, iterable, padvalue=None):
    "grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')"
    return izip_longest(*[iter(iterable)]*n, fillvalue=padvalue)


def convertir(cola):
		lineas = ""
		while not cola.empty():
			lineas = lineas + cola.get()
		cadena = []
		for i in lineas.split('\n'):
			if i != "":
				if i.split(' ')[0] == "space":
					cadena.append([0,0])
				elif i.split(' ')[0] == "pulse":
					cadena.append([0,1])
				cadena[-1][0] = 2 if int(i.split(' ')[1].replace('\n','')) > 800 else 1
		cadena.append([2,1])


		x = [a[0] for a in cadena]
		y = [a[1] for a in cadena]	
		c = []

		comienzo = x.index(1)
		for valor in grouper(2,x[comienzo:-1]):
			if valor[0] == valor[1] == 2:
				c.append(3)
			else:
				c.append(\
					 0 if (valor[0]==valor[1]) else 1
				)
		#c.reverse()
		resultado =  str(c).replace(',','').replace(' ','').replace('3','\n')[1:-1]
		print resultado
		resultado += '\n'
		guardaren = open(Archivo,'a')
		guardaren.write(resultado)
		guardaren.close()

pipe = Popen(["mode2","-d","/dev/lirc0"],stdout=PIPE)
obtenerCadenas(pipe)

